#pragma once

#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>

class Util
{
public:
    static int ReadLine(int sock, std::string &out)
    {
        char ch = 'X';
        while (ch != '\n')
        {
            ssize_t size = recv(sock, &ch, 1, 0);
            if (size > 0)
            {
                if (ch == '\r')
                {
                    recv(sock, &ch, 1, MSG_PEEK);
                    if (ch == '\n')
                        recv(sock, &ch, 1, 0);
                    else
                        ch = '\n';
                }
                out.push_back(ch);
            }
            else if (size == 0)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
        return out.size();
    }

    static bool CurString(const std::string &target, std::string &sub_out1, std::string &sub_out2, std::string sep)
    {
        auto pos = target.find(sep, 0);
        if (pos != target.npos)
        {
            sub_out1 = target.substr(0, pos);
            sub_out2 = target.substr(pos + sep.size());
            return true;
        }
        else
            return false;
    }
};